package com.kanche.bigbaby.collection;

import android.content.Context;
import android.text.InputFilter;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;

import com.kanche.bigbaby.R;

import net.sourceforge.pinyin4j.PinyinHelper;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//import com.kkche.bss.R;

/**
 * Created by nealmi on 6/11/14.
 */
public class StringUtils {
    public static final long MAX_PRICE = 10000000;//1000W
    private static final String YES = "yes";
    private static final String NO = "no";
    private static final Pattern mobilePattern = Pattern.compile("^[1][0-9]{10}$"); // 验证手机号
    private static final long MAX_MILEAGE = 1000000;//100W
    private static String chinaMobiles = "GT-I9508V,SM-N9008";

    public static boolean hasText(String value) {
        return value != null && !"".equals(value.trim());
    }

    public static char getFirstLetterOfPinyin(String source) {
        if (!StringUtils.hasText(source)) {
            return '0';
        }
        try {
            if (source.startsWith("长")) {
                return 'C';
            }
            String[] pinyins = PinyinHelper.toHanyuPinyinStringArray(source.subSequence(0, 1).charAt(0));
            return (pinyins[0].charAt(0) + "").toUpperCase().charAt(0);
        } catch (Exception e) {
            return (source + "").toUpperCase().charAt(0);
        }
    }

    public static String getFirstPinyinLetterAsString(String source) {
        try {
            String[] pinyins = PinyinHelper.toHanyuPinyinStringArray(source.subSequence(0, 1).charAt(0));
            return pinyins[0].substring(0, 1).toUpperCase();
        } catch (Exception e) {
            return (source + "").toUpperCase().substring(0, 1).toUpperCase();
        }
    }

    public static List<String> spilt(String displayValue, String token) {
        List<String> results = new ArrayList<String>();
        StringTokenizer tokenizer = new StringTokenizer(displayValue, token);

        while (tokenizer.hasMoreElements()) {
            results.add(tokenizer.nextElement().toString().trim());
        }
        return results;
    }

    public static String boolToStringYesNo(boolean b) {
        return b ? YES : NO;
    }

    public static boolean yesNoToBool(String yesOrNo) {
        return YES.equalsIgnoreCase(yesOrNo);
    }

    public static int boolToInt(boolean b) {
        return b ? 1 : 0;
    }

    public static boolean intToBool(int yesOrNo) {
        return yesOrNo == 1;
    }

    public static boolean isHttpPath(String path) {
        return hasText(path) && path.startsWith("http");
    }

    public static String boolToDisplay(boolean b) {
        return b ? "是" : "否";
    }

    public static boolean isValidMobile(String mobile) {
        return mobilePattern.matcher(mobile).matches();
    }

    public static String isMobileMode(Context context, String mobile) {
        Pattern p = Pattern.compile(context.getResources().getString(R.string.regula_phonenumber));
        Matcher m = p.matcher(mobile);
        String mobileNum = null;
        if (m.find())
            mobileNum = m.group();
        else
            mobileNum = null;

        return mobileNum;
    }

    public static boolean isLengthBetween(String desc, int start, int end) {
        return (desc.length() >= start && desc.length() <= end);
    }

    public static boolean isValidVIN(final String vin) {
        return vin.length() == 17 ? true : false;
    }

    public static boolean isChinese(String text) {
        boolean chinese = true;
        try {
            int n = Integer.parseInt(text);
            chinese = true;
        } catch (Exception e) {
            char[] cs = text.toCharArray();
            for (char c : cs) {
                //判断是否为汉字。0-126之间的字符都是单字节..
                if ((int) c > 0 && (int) c < 126) {
                    chinese = false;
                    break;
                }
                //判断一些特殊字符（如：@，#，&等）
                if (((int) c < 32 && (int) c > 64) && ((int) c < 91 && (int) c > 96)) {
                    chinese = false;
                    break;
                }
            }
        }
        return chinese;
    }

    public static String transformImageCdnUrl(String url, int width, int height, int quality) {
        url = url.replace("http://pic.kanche.com/", "http://kanche-pic.qiniudn.com/");
        String params = String.format("?imageView2/1/w/%d/h/%d/q/%d", width, height, quality);
        url += params;
        return url;
    }

    public static boolean isValidPrice(String bidPrice) {
        try {
            long value = new BigDecimal(bidPrice).setScale(2, BigDecimal.ROUND_FLOOR).multiply(new BigDecimal(10000)).longValue();

            return value > 0 && value < MAX_PRICE;
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isValidMileage(String mileage) {
        try {
            long value = new BigDecimal(mileage).setScale(2, BigDecimal.ROUND_FLOOR).multiply(new BigDecimal(10000)).longValue();

            return value > 0 && value < MAX_MILEAGE;
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isChinaMobileCustomRom(String model) {
        return true;
        //return chinaMobiles.contains(model);
    }

    public static int toTenK(String price) {
        return new BigDecimal(price)
                .multiply(new BigDecimal(10000))
                .toBigInteger().intValue();
    }

    public static class VINCharacterFilter implements InputFilter {

        public CharSequence filter(CharSequence source, int start, int end,
                                   Spanned dest, int dstart, int dend) {
            for (int i = start; i < end; i++) {
                if (isNotAllowed(source.charAt(i))) {
                    return "";
                }
                if (Character.isLowerCase(source.charAt(i))) {
                    char[] v = new char[end - start];
                    TextUtils.getChars(source, start, end, v, 0);
                    String s = new String(v).toUpperCase();

                    if (source instanceof Spanned) {
                        SpannableString sp = new SpannableString(s);
                        TextUtils.copySpansFrom((Spanned) source,
                                start, end, null, sp, 0);
                        return sp;
                    } else {
                        return s;
                    }
                }
            }

            return null; // keep original
        }

        private boolean isNotAllowed(char c) {
            return (c == 'i' || c == 'I'
                    || c == 'o' || c == 'O'
                    || c == 'q' || c == 'Q');
        }
    }

    public static class LengthFilter implements InputFilter {
        private int mMaxInt;
        private int mMaxPrecision;

        public LengthFilter(int maxInt, int maxPrecision) {
            mMaxInt = maxInt;
            mMaxPrecision = maxPrecision;
        }

        public CharSequence filter(CharSequence source, int start, int end,
                                   Spanned dest, int dstart, int dend) {
            int dotIndex = String.valueOf(dest).indexOf(".");

            if (dotIndex != -1) {

                int intStart = 0;
                int intEnd = dotIndex - 1;
                int pStart = dotIndex + 1;
                if (pStart == dest.length()) {
                    return keep(mMaxInt, dest.length() - 1, intStart, intEnd, source, start, end);
                }

                return keep(mMaxInt + 1 + mMaxPrecision, dest.length(), dstart, dend, source, start, end);
            } else if (source.length() > 0 && source.charAt(0) == '.') {
                return ".";
            } else {
                return keep(mMaxInt, dest.length(), dend, dstart, source, start, end);
            }
        }

        private CharSequence keep(int max, int destLen, int dstart, int dend,
                                  CharSequence source, int start, int end) {
            int keep = max - (destLen - (dend - dstart));

            if (keep <= 0) {
                return "";
            } else if (keep >= end - start) {
                return null; // keep original
            } else {
                keep += start;
                if (Character.isHighSurrogate(source.charAt(keep - 1))) {
                    --keep;
                    if (keep == start) {
                        return "";
                    }
                }
                return source.subSequence(start, keep);
            }
        }

    }

}
